package com.resume.aipeople.controller;

import com.resume.aipeople.controller.AudioController;
import com.resume.aipeople.service.ai.VoiceService;
import com.resume.aipeople.service.ai.asr.SpeechRecognitionStrategy;
import com.resume.aipeople.service.ai.asr.SpeechRecognitionStrategyManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/voice")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class VoiceController {
    
    private final VoiceService voiceService;
    private final SpeechRecognitionStrategyManager strategyManager;
    
    /**
     * 文本转语音
     */
    @PostMapping("/tts")
    public ResponseEntity<Map<String, Object>> textToSpeech(@RequestBody TTSRequest request) {
        try {
            // 参数验证
            if (request.getText() == null || request.getText().trim().isEmpty()) {
                log.warn("TTS请求文本为空");
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("error", "文本内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (request.getCharacterName() == null || request.getCharacterName().trim().isEmpty()) {
                log.warn("TTS请求角色名称为空，使用默认角色");
                request.setCharacterName("默认角色");
            }
            
            log.info("TTS请求: 文本长度={}, 角色={}", request.getText().length(), request.getCharacterName());
            
            String audioUrl = voiceService.textToSpeech(request.getText(), request.getCharacterName())
                    .block();
            
            Map<String, Object> response = new HashMap<>();
            if (audioUrl != null) {
                response.put("success", true);
                response.put("audioUrl", audioUrl);
                log.info("TTS成功生成音频: {}", audioUrl);
            } else {
                // 使用模拟TTS
                audioUrl = voiceService.generateMockAudioUrl(request.getText(), request.getCharacterName());
                response.put("success", true);
                response.put("audioUrl", audioUrl);
                response.put("mock", true);
                response.put("message", "使用模拟TTS服务");
                log.info("TTS使用模拟服务: {}", audioUrl);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("TTS转换失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "TTS转换失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 语音转文本（语音通话专用，支持策略选择）
     */
    @PostMapping("/voice-call/asr")
    public ResponseEntity<Map<String, Object>> voiceCallSpeechToText(
            @RequestParam("audio") MultipartFile audioFile,
            @RequestParam(value = "strategy", required = false) String strategyName) {
        try {
            if (audioFile.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("error", "音频文件为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 获取指定的语音识别策略
            SpeechRecognitionStrategy strategy = strategyManager.getStrategy(strategyName);
            log.info("语音通话使用语音识别策略: {} ({})", strategy.getDisplayName(), strategy.getStrategyName());
            
            log.info("语音通话ASR请求 - 文件名: {}, 大小: {}KB", 
                    audioFile.getOriginalFilename(), audioFile.getSize() / 1024);
            
            String text = strategy.speechToText(audioFile).block();
            
            Map<String, Object> response = new HashMap<>();
            if (text != null && !text.trim().isEmpty()) {
                response.put("success", true);
                response.put("text", text);
                response.put("strategy", strategy.getStrategyName());
                response.put("strategyDisplayName", strategy.getDisplayName());
                response.put("message", "语音识别成功");
                log.info("语音通话{}识别成功: {}", strategy.getDisplayName(), text);
            } else {
                response.put("success", false);
                response.put("error", "语音识别失败，请重试");
                response.put("strategy", strategy.getStrategyName());
                response.put("strategyDisplayName", strategy.getDisplayName());
                log.warn("语音通话{}识别失败", strategy.getDisplayName());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("语音通话ASR转换失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "语音识别服务异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 语音转文本（支持策略选择）
     */
    @PostMapping("/asr")
    public ResponseEntity<Map<String, Object>> speechToText(
            @RequestParam("audio") MultipartFile audioFile,
            @RequestParam(value = "strategy", required = false) String strategyName) {
        try {
            if (audioFile.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("error", "音频文件为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 获取指定的语音识别策略
            SpeechRecognitionStrategy strategy = strategyManager.getStrategy(strategyName);
            log.info("使用语音识别策略: {} ({})", strategy.getDisplayName(), strategy.getStrategyName());
            
            // 保存音频文件用于测试和调试
            String savedAudioId = AudioController.saveASRAudioData(audioFile);
            log.info("语音输入音频已保存: {}, 原始文件名: {}, 大小: {}KB", 
                    savedAudioId, audioFile.getOriginalFilename(), audioFile.getSize() / 1024);
            
            String text = strategy.speechToText(audioFile).block();
            
            Map<String, Object> response = new HashMap<>();
            if (text != null && !text.trim().isEmpty()) {
                response.put("success", true);
                response.put("text", text);
                response.put("strategy", strategy.getStrategyName());
                response.put("strategyDisplayName", strategy.getDisplayName());
                response.put("audioId", savedAudioId);
                response.put("audioUrl", "/api/audio/asr/" + savedAudioId);
                response.put("audioInfo", "/api/audio/asr/info/" + savedAudioId);
                log.info("{}识别成功: {}", strategy.getDisplayName(), text);
            } else {
                // 识别失败，返回失败状态
                response.put("success", false);
                response.put("error", "语音识别失败，请重试");
                response.put("strategy", strategy.getStrategyName());
                response.put("strategyDisplayName", strategy.getDisplayName());
                response.put("audioId", savedAudioId);
                response.put("audioUrl", "/api/audio/asr/" + savedAudioId);
                response.put("audioInfo", "/api/audio/asr/info/" + savedAudioId);
                log.warn("{}识别失败，返回空结果", strategy.getDisplayName());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("ASR转换失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "语音识别失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取可用的语音识别策略
     */
    @GetMapping("/strategies")
    public ResponseEntity<Map<String, Object>> getAvailableStrategies() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("strategies", strategyManager.getAvailableStrategies());
        response.put("defaultStrategy", strategyManager.getDefaultStrategy().getStrategyName());
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取支持的语音列表
     */
    @GetMapping("/voices")
    public ResponseEntity<Map<String, Object>> getSupportedVoices() {
        Map<String, Object> response = new HashMap<>();
        response.put("voices", new String[]{
            "young_male_en", "wise_male_cn", "professional_female_cn", "default_cn"
        });
        return ResponseEntity.ok(response);
    }
    
    // TTS请求类
    public static class TTSRequest {
        private String text;
        private String characterName;
        
        public String getText() { return text; }
        public void setText(String text) { this.text = text; }
        
        public String getCharacterName() { return characterName; }
        public void setCharacterName(String characterName) { this.characterName = characterName; }
    }
} 